<template>
  <div class="login">
    <el-row>
      <el-col :span="8" :offset="8">
        <div class="log-div">
          <h3 class="title">小U商城后台管理系统</h3>
          <!-- model：表单的数据 -->
          <!-- rules：表单校验的验证规则 -->
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="0px"
            class="demo-ruleForm"
          >
            <!-- label：提示文本 -->
            <!-- prop：对应的数据 -->
            <el-form-item prop="username">
              <el-input v-model="ruleForm.username">
                <el-button slot="prepend" icon="el-icon-user"></el-button>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model="ruleForm.password" show-password>
                <el-button slot="prepend" icon="el-icon-lock"></el-button>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                class="btn"
                type="primary"
                @click="submitForm('ruleForm')"
                >立即登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {loginFn} from '../apis'
export default {
  data() {
    return {
      // 表单的数据
      ruleForm: {
        username: "123456",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      // this.$refs[formName]获取表单的dom节点
      // validate 校验函数，element 自带的函数
      this.$refs[formName].validate((valid) => {
        // valid 校验的结果
        if (valid) {
          this.login()
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async login() {
      let res = await loginFn(this.ruleForm);
      // 登录成功后先保存数据，然后跳转
      this.$store.commit('setUserInfo', res.list);
      this.$router.push('/')
    }
  }
};
</script>

<style>
.login {
  width: 100vw;
  height: 100vh;
  background-image: url("../assets/loginbg.jpeg");
}
.log-div {
  background-color: #fff;
  height: 300px;
  border-radius: 8px;
  margin-top: 200px;
}
.title {
  text-align: center;
  color: #fb6d49;
}
.login .btn {
  width: 100%;
}
</style>